<template>
  <!-- router  不建议用router  影响刷新打开默认路由 -->
  <el-menu
    :default-active="router.currentRoute.value.path"
    :unique-opened="true"
    class="el-menu-vertical-demo"
    router
  >
    <template v-for="item in menu">
      <!-- 如果有子集 -->
      <template v-if="item.children && item.children.length > 0">
        <el-sub-menu
          :key="item.id"
          :index="item.path"
          :disabled="item.meta?.disabled"
          :popper-append-to-body="false"
        >
          <template #title>
            <i :class="[item.meta?.icon]"></i>
            <!-- 添加空格 表示下级-->
            <span> {{ generateSpaces(item.level) }} sdfsd</span>
            <span slot="title"> {{ item.name }}</span>
          </template>
          <MenuTree
            :menu="item.children"
            :defaultActive="router.currentRoute.value.path"
            @clickItem="clickItemHandle"
          />
        </el-sub-menu>
      </template>
      <!-- 如果没有子集 -->
      <template v-else>
        <el-menu-item
          :key="item.id"
          :index="item.path"
          :disabled="item.meta?.disabled"
          :popper-append-to-body="false"
          @click="clickItemHandle(item)"
        >
          <i :class="[item.meta?.icon]"></i>
          <!-- 添加空格 表示下级-->
          <span> {{ generateSpaces(item.level) }} </span>
          <span slot="title">{{ item.name }}</span>
        </el-menu-item>
      </template>
    </template>
  </el-menu>
</template>
   
  <script  name="MenuTree" setup>
// 把下面代码变成setup语法糖的形式
import { ref, reactive } from "vue";
import { useRouter, useRoute } from "vue-router";

// router是全局路由对象
let router = useRouter();
// 获取全部路由
// route是当前路由对象
let route = useRoute();
// console.log(
//   router.currentRoute.value,
//   "router.currentRoute.value.path",
//   router.currentRoute.value.meta.id
// );

// type 为了方便写成这样 可以根据自己项目设定type
defineProps({
  menu: {
    type: Array,
    required: true,
    default: () => [],
  },
  // defaultActive: {
  //   type: String,
  //   required: true,
  //   default: [],
  // },
});

const emit = defineEmits(["update-active-path", "clickItem"]);

// 返回的空格字符串 用于显示菜单层级
const generateSpaces = (level) => {
  let str = "";
  level
    .split("")
    .filter((it) => it != "-")
    .forEach(() => {
      str += "　";
    });
  return str;
};

// 点击当前菜单项
const clickItemHandle = (item) => {
  emit("clickItem", item);
};
</script>
   
  <style scoped lang="scss">
</style>